package servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.Blog;
import model.BlogDao;
import model.User;
import model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/getAuthorInfo")
public class AuthorServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
      String blogId = req.getParameter("blogId");
      if(blogId==null){
          resp.setContentType("text/html; charset=utf8");
          resp.getWriter().write("请求中缺少blogId");
          return;
      }

        BlogDao blogDao = new BlogDao();
        try {
            Blog blog = blogDao.getBlog(Integer.parseInt(blogId));
            if(blog==null){
                resp.setContentType("text/html; charset=utf8");
                resp.getWriter().write("blogId没有找到");
                return;
            }
            UserDao userDao = new UserDao();
            User user = userDao.getUserById(blog.getUserId());
            if(user==null){
                resp.setContentType("text/html; charset=utf8");
                resp.getWriter().write("blogId没有找到");
                return;
            }
              user.setPassword("");
            String reJson = objectMapper.writeValueAsString(user);
            resp.setContentType("application/json; charset=utf8");
            System.out.println("1111");
            resp.getWriter().write(reJson);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }
}
